import subprocess

# A utility class that trains and returns the weights of
# the learned polynomial given the regularization value.
class Trainer():

  def __init__(self, learn_script = './learn_script',
      master_train_filepath = './D.dat', weights_out = './w.dat'):
    self.learn_script = learn_script
    self.master_train_filepath = master_train_filepath
    self.weights_out = weights_out

  def train(self, training_files, regularization):
    # Remove the master_train_filepath if any.
    subprocess.call(['rm', '-rf', self.master_train_filepath]) 

    # Create the master train file.
    master_train_file = open(self.master_train_filepath, 'w')
    for training_file in training_files:
      subprocess.check_call(['cat', '%s' % training_file],
          stdout = master_train_file)
    master_train_file.close()

    # Train command
    regularization_str = 'exp(%d)' % regularization
    train_command = [self.learn_script, regularization_str] 

    # Train
    subprocess.check_call(train_command)

    # Read the weights
    weights = []
    weight_strings = open(self.weights_out, 'r').read().strip().split('\n')
    for weight_string in weight_strings:
      weights.append(round(float(weight_string), 2))

    return weights
